package com.iweb.dao;

import com.iweb.pojo.Good;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/*
 *作者：lth
 *时间：2020/8/11 16:59
 *描述：
 */
public class GoodDaoImpl implements GoodDao{

    private Connection connection;

    public GoodDaoImpl(Connection connection) {
        this.connection= connection;
    }

    @Override
    public List<Good> selectList(String title) throws Exception {
        List<Good> goods = new ArrayList<>();
        String sql = "select * from tb_good ";

        if(title!=null){
            sql += "where title like ?";
        }

        PreparedStatement pst = connection.prepareStatement(sql);

        if(title!=null){
            pst.setObject(1,"%"+title+"%");
        }

        ResultSet rs = pst.executeQuery();

        Good good = null;
        while (rs.next()){
            good = createGood(rs);
            goods.add(good);
        }

        return goods;
    }

    @Override
    public Good selectListbyGid(String gid) throws Exception {
        List<Good> goods = new ArrayList<>();
        String sql = "select * from tb_good where gid =?";



        PreparedStatement pst = connection.prepareStatement(sql);


            pst.setObject(1,gid);


        ResultSet rs = pst.executeQuery();

        Good good = null;
        while (rs.next()){
            good = createGood(rs);
        }

        return good;
    }

    private Good createGood(ResultSet rs) throws Exception{
        Good good = new Good();
        good.setGid(rs.getString(1));
        good.setTitle(rs.getString(2));
        good.setPrice(rs.getDouble(3));
        good.setContent(rs.getString(4));
        good.setCid(rs.getString(5));
        return good;
    }
}
